package com.leetcode;

import com.leetcode.common.TreeNode;
import com.leetcode.util.BinaryTreeUtil;
import javafx.util.Pair;

import java.util.*;

/**
 * 102. 二叉树的层序遍历
 * 广度优先搜索, 记录节点所在的层
 *
 * @author fy
 * @date 2022/4/14 19:56
 */
public class Solution102_1 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<Pair<TreeNode, Integer>> queue = new LinkedList<>();
        queue.offer(new Pair<>(root, 0));
        while (!queue.isEmpty()) {
            Pair<TreeNode, Integer> pair = queue.poll();
            TreeNode node = pair.getKey();
            int level = pair.getValue();
            if (level == res.size()) {
                res.add(new ArrayList<>());
            }
            res.get(level).add(node.val);
            if (node.left != null) {
                queue.offer(new Pair<>(node.left, level + 1));
            }
            if (node.right != null) {
                queue.offer(new Pair<>(node.right, level + 1));
            }
        }
        return res;
    }

    public static void main(String[] args) {
        Integer[] nums = new Integer[]{3, 9, 20, null, null, 15, 7};
        TreeNode root = BinaryTreeUtil.createTree(nums);
        BinaryTreeUtil.printTree(root);

        List<List<Integer>> res = new Solution102_1().levelOrder(root);
        System.out.println(res);
    }
}
